package 
{
	import flash.utils.Dictionary;
	
	public final class ObjectPool
	{
		private static var poolLookup:Dictionary;
		
		public static function addObject(gameObject:Object):void
		{
			trace("Before Add "+Object(gameObject).constructor + " pool size: " + poolLookup[Object(gameObject).constructor].length);			
			poolLookup[Object(gameObject).constructor].push(gameObject);			
			trace("After Add "+Object(gameObject).constructor + " pool size: " + poolLookup[Object(gameObject).constructor].length);
		}
		
		public static function getObject(desiredClass:Class):Object
		{
			trace("Before Get "+desiredClass+" pool size: " + poolLookup[desiredClass].length);
			if (poolLookup == null ||
				poolLookup[desiredClass] == null ||
				poolLookup[desiredClass].length == 0)
				return null;
				
				return poolLookup[desiredClass].pop();
							
		}
		
		public static function fillPool(desiredClass:Class, amount:int, data:Object=null):void
		{
			if (poolLookup == null)
				poolLookup = new Dictionary();
			
			var objectPool:Array = poolLookup[desiredClass];
			
			if (objectPool == null)
				objectPool = poolLookup[desiredClass] = new Array();
			
			for (var i:int = 0; i < amount; i += 1)
				objectPool.push(new desiredClass(data));
			
		}
		
		public static function clearPools():void
		{		
			var poolLength:uint = poolLookup.length;
			for each(var it:Object in poolLookup)
			{
				var itLength:uint = it.length;
				for(var idx:uint = 0; idx < itLength; ++idx)
				{
					(it[idx] as GameObject).dispose();	
				}				
			}
			poolLookup = null;
		}
	}	
}